<script setup lang="ts">
import { ref, useTemplateRef } from 'vue'
import VideoWrap from '../../components/video-wrap.vue'
import { useGsapContext } from '@/hooks'
import { ScrollTrigger } from 'gsap/ScrollTrigger'
import { useScrollGroup } from '@/hooks/reno14-pro.ts'
import { useIntersectionObserver } from '@vueuse/core'

defineProps<{
  videoSrc: string
  mainTitle: string
  subtitle: string
}>()

const { scrollGroup } = useScrollGroup()

const containerRef = useTemplateRef<HTMLDivElement | null>('containerRef')
const videoRef = useTemplateRef<HTMLVideoElement | null>('videoRef')

useIntersectionObserver(videoRef, ([{ isIntersecting }]) => {
  if (!isIntersecting) {
    const video = videoRef.value
    if (video) {
      video.pause()
      video.currentTime = 0
    }
  }
})

useGsapContext(() => {
  if (!containerRef.value) {
    return
  }

  ScrollTrigger.create({
    trigger: containerRef.value,
    start: 'top center',
    end: 'bottom center',
    onToggle: async (self) => {
      const video = videoRef.value

      if (self.isActive && video) {
        await video.play().catch()
      }
    },
    invalidateOnRefresh: true,
    ...scrollGroup,
  })
})

const playing = ref(false)
</script>

<template>
  <div ref="containerRef">
    <VideoWrap class="w-full aspect-[25/33] lg:aspect-[180/239]" :playing>
      <video
        ref="videoRef"
        class="w-full h-full object-cover"
        muted
        @play="playing = true"
        @ended="playing = false"
        :src="videoSrc"
      ></video>
    </VideoWrap>

    <div class="mt-[0.875rem]">
      <p class="text-lg lg:text-[clamp(1.125rem,0.375rem+1.1719vw,1.5rem)]">{{ mainTitle }}</p>
      <p
        class="text-xs text-white opacity-75 leading-[1.66] lg:text-[clamp(0.75rem,0.25rem+0.7813vw,1rem)]"
      >
        {{ subtitle }}
      </p>
    </div>
  </div>
</template>
